<?php
namespace app\common\service\order;
use app\common\cache\order\TblmOrderCache;
use app\common\model\order\TblmOrderModel;
use app\common\service\member\MemberService;
use app\common\service\member\SettingService as MemberSettingService;
use app\common\service\system\SettingService;
use think\facade\Db;
use thirdsdk\Http;

/**
 * 淘宝联盟订单
 */
class TblmOrderService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
            'id' => '',
        'member_id' => '',
        'is_disable' => '',
        'item_id' => '',
        'trade_id' => '',
        'tb_paid_time' => '',
        'tk_paid_time' => '',
        'pay_price' => '',
        'pub_share_fee' => '',
        'tk_order_role' => '',
        'tk_earning_time' => '',
        'adzone_id' => '',
        'plat_type' => '',
        'pub_share_rate' => '',
        'refund_tag' => '',
        'subsidy_rate' => '',
        'tk_total_rate' => '',
        'item_category_name' => '',
        'seller_nick' => '',
        'pub_id' => '',
        'alimama_rate' => '',
        'subsidy_type' => '',
        'item_img' => '',
        'pub_share_pre_fee' => '',
        'alipay_total_price' => '',
        'item_title' => '',
        'site_name' => '',
        'item_num' => '',
        'subsidy_fee' => '',
        'alimama_share_fee' => '',
        'trade_parent_id' => '',
        'order_type' => '',
        'tk_create_time' => '',
        'flow_source' => '',
        'terminal_type' => '',
        'click_time' => '',
        'tk_status' => '',
        'item_price' => '',
        'adzone_name' => '',
        'total_commission_rate' => '',
        'item_link' => '',
        'site_id' => '',
        'seller_shop_title' => '',
        'income_rate' => '',
        'total_commission_fee' => '',
        'tk_commission_pre_fee_for_media_platform' => '',
        'tk_commission_fee_for_media_platform' => '',
        'tk_commission_rate_for_media_platform' => '',
        'special_id' => '',
        'relation_id' => '',
        'tk_deposit_time' => '',
        'tb_deposit_time' => '',
        'deposit_price' => '',
        'taobao_user_id' => '',
        'status' => '',
        'settlement_price' => '',
        'settlement_time' => '',
        'settlement_uid' => '',
    ];
    /**
     * 淘宝联盟订单列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new TblmOrderModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,member_id,is_disable,create_time,update_time,item_id,trade_id,tb_paid_time,tk_paid_time,pay_price,pub_share_fee,tk_order_role,tk_earning_time,adzone_id,plat_type,pub_share_rate,refund_tag,subsidy_rate,tk_total_rate,item_category_name,seller_nick,pub_id,alimama_rate,subsidy_type,item_img,pub_share_pre_fee,alipay_total_price,item_title,site_name,item_num,subsidy_fee,alimama_share_fee,trade_parent_id,order_type,tk_create_time,flow_source,terminal_type,click_time,tk_status,item_price,adzone_name,total_commission_rate,item_link,site_id,seller_shop_title,income_rate,total_commission_fee,tk_commission_pre_fee_for_media_platform,tk_commission_fee_for_media_platform,tk_commission_rate_for_media_platform,special_id,relation_id,tk_deposit_time,tb_deposit_time,deposit_price,taobao_user_id,status,settlement_price,settlement_time,settlement_uid,promotion_total,refund_msg,refresh_num';
        }
        if (empty($order)) {
            $order = [$pk => 'desc'];
        }
        if ($page == 0 || $limit == 0) {
            return $model->field($field)->where($where)->order($order)->select()->toArray();
        }
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        //根据状态查询数量
        $where_num = " where is_delete=0 and is_disable=0";
        $status_num = Db::query("SELECT status,count(id) as num from ya_tblm_order ".$where_num." GROUP BY status");
        $status = [
            'all'=>0,
            'status_0'=>0,
            'status_1'=>0,
            'status_2'=>0,
            'status_3'=>0,
        ];
        foreach ($status_num as $k=>$v){
            $status['all'] = $status['all']+$v['num'];
            $status['status_'.$v['status']] =$v['num'];
        }
        return compact('count', 'pages', 'page', 'limit', 'list','status');
    }
    /**
     * 淘宝联盟订单信息
     *
     * @param int  $id   淘宝联盟订单id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = TblmOrderCache::get($id);
        if (empty($info)) {
            $model = new TblmOrderModel();
            $info = $model->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('淘宝联盟订单不存在：' . $id);
                }
                return [];
            }
            $info = $info->toArray();
            TblmOrderCache::set($id, $info);
        }
        return $info;
    }
    /**
     * 淘宝联盟订单信息
     *
     * @param int  $trade_id   淘宝联盟订单id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function getInfo($trade_id, $exce = true)
    {
        $info = TblmOrderCache::get($trade_id);
        if (empty($info)) {
            $model = new TblmOrderModel();
            $info = $model->where('trade_id',$trade_id)->find();
            if (empty($info)) {
                if ($exce) {
                    exception('返利订单不存在：' . $trade_id);
                }
                return [];
            }
            $info = $info->toArray();
            TblmOrderCache::set($trade_id, $info);
        }
        return $info;
    }

    /**
     * 根据条件查询数量
     * @Author: 易军辉
     * @DateTime:2024-11-06 20:04
     * @param $where 条件
     * @return int
     * @throws \think\db\exception\DbException
     */
    public static function getCountByWhere($where)
    {
        $model = new TblmOrderModel();
        return $model->where($where)->count();
    }
    /**
     * 淘宝联盟订单添加
     *
     * @param array $param 淘宝联盟订单信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new TblmOrderModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();
        $model->save($param);
        $id = $model->$pk;
        if (empty($id)) {
            exception();
        }
        $param[$pk] = $id;
        return $param;
    }
     /**
     * 淘宝联盟订单修改
     *
     * @param int|array $ids   淘宝联盟订单id
     * @param array     $param 淘宝联盟订单信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new TblmOrderModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        TblmOrderCache::del($ids);
        return $param;
    }
    /**
     * 淘宝联盟订单删除
     *
     * @param array $ids  淘宝联盟订单id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new TblmOrderModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        TblmOrderCache::del($ids);
        return $update;
    }

    /**
     * 淘宝联盟订单结算
     * @Author: 易军辉
     * @DateTime:2024-11-06 12:02
     * @param $ids 订单ids
     * @return mixed
     * @throws \think\Exception
     */
    public static function settlementOrder($ids)
    {
        $model = new TblmOrderModel();
        $pk = $model->getPk();
        // 启动事务
        $model->startTrans();
        try {
            $list = $model->where($pk, 'in', $ids)
                ->where('status',0)
//                ->where('tk_status',0)
                ->where('is_disable',0)
                ->where('is_delete',0)
                ->select();
            if(count($list)<=0){
                exception("未有符合条件的订单进行结算");
            }
            foreach ($list as $key=>$val){
                //支付买家佣金
                $commission_res = MemberService::income(
                    $val['member_id'],
                    $val['settlement_price'],
                    0,
                    $val['settlement_price'],
                    null,//订单佣金返款
                    $val['id'],
                    null,
                    '返利订单：'.$val['trade_id'],
                    'PTBT'
                );
                //计算推广费
                $edit_data = self::payPromotionFee($val,$val['settlement_price']);
                $edit_data['status']=1;
                $edit_data['settlement_time']=date('Y-m-d H:i:s');
                $model->where($pk,$val[$pk])->update($edit_data);
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        $param['ids'] = $ids;
        TblmOrderCache::del($ids);
        return $param;
    }
    /**
     * 推广费用结算
     * @Author: 易军辉
     * @DateTime:2024-09-11 16:46
     * @param $order
     */
    private static function payPromotionFee($order,$basic_price)
    {
        $promotion_data = [
            'member_remark'=>"",
            'promotion_total'=>0
        ];
        /******************************买家分销******************************************************/
        $setting = MemberSettingService::info('is_distribution,distribution_mode');
        if($setting['is_distribution']==1 && $order['member_id']){//开启分销
            //查询上级会员
            $member =  Db::name('member')
                ->where('member_id',$order['member_id'])
                ->field('member_id,pid')
                ->find();
            $pid_members = self::member_pid($member['pid'],0,[],$setting['distribution_mode']);
            foreach ($pid_members as $key=>$val){
                //计算佣金
                $amount = 0;
                if($val['rebate_type'] ==1){
                    //固定返佣
                    $amount = $val['rebate'];
                }else if($val['rebate_type'] ==2){
                    //比例返佣
                    $amount =bcmul($basic_price, bcdiv($val['rebate'], 100,4),2);
                }
                //备注推荐人等级编码
                if($promotion_data['member_remark']!=""){
                    $promotion_data['member_remark'] .=",";
                }
                $promotion_data['member_remark'] .="level".$val['level'].":".$val['code'];
                if($amount<=0){
                    continue;
                }
                switch ($val['level']){
                    case 1:
                        $promotion_data['one_member_id'] = $val['member_id'];
                        $promotion_data['one_amount'] = $amount;
                        break;
                    case 2:
                        $promotion_data['two_member_id'] = $val['member_id'];
                        $promotion_data['two_amount'] = $amount;
                        break;
                    case 3:
                        $promotion_data['three_member_id'] = $val['member_id'];
                        $promotion_data['three_amount'] = $amount;
                        break;
                }
                //计算总金额
                $promotion_data['promotion_total'] = bcadd($promotion_data['promotion_total'],$amount,2);
                //转账
                $commission_res = MemberService::income(
                    $val['member_id'],
                    $amount,
                    0,
                    $amount,
                    null,//推广佣金
                    $order['id'],
                    null,
                    '返利订单：'.$order['trade_id'],
                    'XJTC'
                );
            }
        }
        return $promotion_data;
    }
    /**
     * 查询买家上级
     * @Author: 易军辉
     * @DateTime:2024-09-12 10:27
     * @param $member_id 上级买家id
     * @param $level 等级
     * @param $result 查询结果
     * @param $distribution_mode 分销等级
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private static function member_pid($member_id=0,$level=0, $result = [],$distribution_mode = 1)
    {
        // 如果当前级别已经达到分销等级，停止递归
        if ($level >= $distribution_mode) {
            return $result;
        }
        $member =  Db::name('member')->alias('a')
            ->leftJoin('member_distribution','a.member_distribution_id = member_distribution.id')
            ->where('a.is_disable',0)
            ->where('a.is_delete',0)
            ->where('member_distribution.is_disable',0)
            ->where('member_distribution.is_delete',0)
            ->where('a.member_id',$member_id)
            ->field('a.member_id,
                    a.pid,
                    member_distribution.code,
                    member_distribution.rebate_type,
                    member_distribution.rebate_one,
                    member_distribution.rebate_two,
                    member_distribution.rebate_three,
                    member_distribution.setting_store_platform_ids
            ')->find();
        if(!$member){
            return $result;
        }
        $level +=1;
        $rebate = 0;
        switch ($level){
            case 1:
                $rebate = $member['rebate_one'];
                break;
            case 2:
                $rebate = $member['rebate_two'];
                break;
            case 3:
                $rebate = $member['rebate_three'];
                break;
        }
        $result[] = [
            'member_id'=>$member['member_id'],
            'pid'=>$member['pid'],
            'level'=>$level,
            'code'=>$member['code'],
            'rebate_type'=>$member['rebate_type'],
            'rebate'=>$rebate,
            'setting_store_platform_ids'=>$member['setting_store_platform_ids'],
        ];
        return self::member_pid($member['pid'],$level,$result,$distribution_mode);
    }
    /**
     * 淘宝联盟订单退款
     * @Author: 易军辉
     * @DateTime:2024-11-06 12:02
     * @param $ids 订单ids
     * @return mixed
     * @throws \think\Exception
     */
    public static function refundtOrder($ids,$param)
    {
        $model = new TblmOrderModel();
        $pk = $model->getPk();
        // 启动事务
        $model->startTrans();
        try {
            $list = $model->where($pk, 'in', $ids)
                ->where('status',1)
                ->where('is_disable',0)
                ->where('is_delete',0)
                ->where('settlement_price','>',0)
                ->select();
            if(count($list)<=0){
                exception("未有符合条件的订单进行退款");
            }
            foreach ($list as $key=>$val){
                //扣除买家佣金
                $consumption_res = MemberService::consumption(
                    $val['member_id'],
                    $val['settlement_price'],
                    0,
                    $val['settlement_price'],
                    null,//撤销订单扣佣金
                    $val['id'],
                    null,
                    "返利订单退款：".$val['trade_id'],
                    'PTBT'
                );
                //买家推广
                if($val['one_member_id'] && $val['one_amount']>0){
                    $res = self::refundOrderPromotion($val['one_member_id'],$val['one_amount'],$val['id'],$val['trade_id']);
                }
                if($val['two_member_id'] && $val['two_amount']>0){
                    $res = self::refundOrderPromotion($val['two_member_id'],$val['two_amount'],$val['id'],$val['trade_id']);
                }
                if($val['three_member_id'] && $val['three_amount']>0){
                    $res = self::refundOrderPromotion($val['three_member_id'],$val['three_amount'],$val['id'],$val['trade_id']);
                }
                $model->where($pk,$val[$pk])->update([
                    'status'=>2,
                    'refund_msg'=>$param['refund_msg'],
                    'update_time'=>datetime()
                ]);
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        $param['ids'] = $ids;
        TblmOrderCache::del($ids);
        return $param;
    }

    /**
     * 扣除推广费
     * @Author: 易军辉
     * @DateTime:2024-11-06 21:02
     * @param $member_id 买家id
     * @param $amount 金额
     * @param $order_id 淘宝联盟订单id
     * @param $trade_id 订单号
     * @return array|false
     */
    private static function refundOrderPromotion($member_id=0,$amount=0,$order_id=0,$trade_id=0)
    {
        if($member_id && $amount>0){
            return MemberService::consumption(
                $member_id,
                $amount,
                0,
                $amount,
                null,//撤销订单扣除推广佣金
                $order_id,
                null,
                "撤销返利订单：".$trade_id,
                'XJTC'
            );
        }
        return false;
    }
    /**
     * 淘宝联盟订单更新
     * @Author: 易军辉
     * @DateTime:2024-11-06 12:02
     * @param $ids 订单ids
     * @return mixed
     * @throws \think\Exception
     */
    public static function refreshOrder($ids)
    {
        $model = new TblmOrderModel();
        $pk = $model->getPk();
        // 启动事务
        $model->startTrans();
        try {
            $list = $model->where($pk, 'in', $ids)
                ->whereIn('status',[0,1])
                ->where('tk_status','<>',13)
                ->where('is_disable',0)
                ->where('is_delete',0)
                ->select();
            if(count($list)<=0){
                exception("未有符合条件的订单进行更新");
            }
            foreach ($list as $key=>$val){
                $data = self::getTblm($val['trade_id']);
                if(count($data)>0){
                    $data['refresh_num'] = $val['refresh_num']+1;
                    $data['update_time'] =datetime();
                    //查看订单是否已失效
                    if(isset($data['tk_status']) && $data['tk_status']==13 && $data['status']==0){
                        $data['status']=3;
                    }
                    $model->where($pk,$val[$pk])->update($data);
                }
            }
            // 提交事务
            $model->commit();
        } catch (\Exception $e) {
            $errmsg = $e->getMessage();
            // 回滚事务
            $model->rollback();
        }

        if (isset($errmsg)) {
            exception($errmsg);
        }
        $param['ids'] = $ids;
        TblmOrderCache::del($ids);
        return $param;
    }

    /**
     * 订单信息查询
     * @Author: 易军辉
     * @DateTime:2024-11-07 14:12
     * @param $order_on
     * @return array|mixed
     */
    private static function getTblm($order_on)
    {
        $http = new Http('submitOrder');
        $setting = SettingService::info('tblm_order_url,tblm_api_key,tblm_appid,tblm_app_secret,tblm_service_price,tblm_subsidy_ratio,tblm_subsidy_price');
        $date = date('Y-m-d H:i:s');
        $body = [
            "method"=>"query.order",
            "app_id"=>$setting['tblm_appid'],
            "date"=>$date,
            "tradeid"=>$order_on,
            "get_orders"=>0,//是否获取全部子订单（0.否；1.是）注：获取子订单结构将会改变
        ];
        /*********************************************签名********************************************/
        ksort($body);
        $stringToBeSigned = '';
        foreach($body as $k => $v)
        {
            $stringToBeSigned .= "$k$v";
        }
        $body['sign'] = strtoupper(md5($stringToBeSigned.$setting['tblm_app_secret']));
        $headers = [];
        $api_res  = $http->post($setting['tblm_order_url'],$body,$headers);
        $data =[];
        if(isset($api_res['data']) && count($api_res['data'])>0){
            $data=$api_res['data'];
            //结算金额计算
            $subsidy =isset($data['pub_share_fee'])?$data['pub_share_fee']:0;
            //平台服务费
            if($setting['tblm_service_price']>0 && $subsidy>0){
                $tblm_service_price = bcdiv(($subsidy*$setting['tblm_service_price']),100,2);
                $subsidy =bcsub($subsidy,$tblm_service_price,2);
            }
            //用户补贴
            if($setting['tblm_subsidy_ratio']>0 && $subsidy>0){
                $subsidy =bcdiv(($subsidy*$setting['tblm_subsidy_ratio']),100,2);
            }
            //额外补贴
            if($setting['tblm_subsidy_price']>0){
                $subsidy =bcadd($subsidy, $setting['tblm_subsidy_price'],2);
            }
            $data['settlement_price'] =$subsidy;
        }
        return $data;
    }
}
